$(function () {

    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/jxstudent/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 50, key: true},
            {label: '头像', name: 'icon', index: 'icon', width: 80,formatter:function (cellvalue, options, rowObject) {
                    return "<img src="+cellvalue+" style='width: 50px; height: 50px' />";
                }},
            {label: '学生姓名', name: 'name', index: 'name', width: 80},
            {label: '学院', name: 'schoolName', index: 'school_id', width: 80},
            {label: '班级', name: 'className', index: 'class_id', width: 80},
            {label: '性别', name: 'sex', index: 'sex', width: 80,formatter:function (cellvalue, options, rowObject) {
                    return cellvalue=="0"?"男":"女";
                }},
            {label: '手机号', name: 'phoneNum', index: 'phone_num', width: 80},
            {label: '学号', name: 'studentNum', index: 'student_num', width: 80},
            {label: '创建时间', name: 'createTime', index: 'create_time', width: 80},
            {label: '更新时间', name: 'updateTime', index: 'update_time', width: 80}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        shrinkToFit:true,
        autoScroll: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            //$("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "scroll"});
        }
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;


var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            name: null
        },
        showList: true,
        title: null,
        jxStudent: {classId: 0, schoolId: 0},
        treeData: {},
        parentNames: {}, // 所有父级名称
        parentIds: {}, //  所有父级id
        treeMap:{} // 所有的树id-name

    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.jxStudent = {className: "请选择"};
            vm.getDept();
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getDept();
            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            console.log(vm.jxStudent);
            $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function () {
                var url = vm.jxStudent.id == null ? "sys/jxstudent/save" : "sys/jxstudent/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.jxStudent),
                    success: function (r) {
                        if (r.code === 0) {
                            layer.msg("操作成功", {icon: 1});
                            vm.reload();
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        } else {
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                if (!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "sys/jxstudent/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            } else {
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function () {
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "sys/jxstudent/info/" + id, function (r) {
                vm.jxStudent = r.jxStudent;
                vm.jxStudent.className = vm.parentNames[r.jxStudent.classId];

                console.log(r.jxStudent.classId);
                console.log(vm.parentNames);
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
        },
        imp: function () {   //  批量导入功能
            vm.jxStudent = {className: "请选择"};
            vm.getDept(); //  初始化treeData
            layer.open({
                type: 1,
                shade: false,
                title: false, //不显示标题
                area: ['600px', '450px'],
                content: $('#imp'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                cancel: function () {

                }
            })

        }, upload: function () {
            $("#text_msg").hide();  // 先隐藏
            var myform = new FormData();
            myform.append('file', $("#file")[0].files[0]);
            var classId = vm.jxStudent.classId ? vm.jxStudent.classId : 0;
            var schoolId = vm.jxStudent.schoolId ? vm.jxStudent.schoolId : 0;
            myform.append('classId', classId);
            myform.append('schoolId', schoolId);
            $.ajax({
                url: baseURL + "sys/jxstudent/upload",//"http://192.168.5.206:8983/solr/update/extract",
                type: "POST",
                data: myform,
                async: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    debugger;
                    if (result.code == 200) {
                        layer.msg("执行成功！", {icon: 1});
                        vm.reload();
                    } else {
                        if (result.code == 500) {
                            layer.msg(result.msg, {icon: 1});
                        }
                        if (result.code == 505) {
                            $("#text_msg").show();  // 显示
                            $("#msgText").val(result.msg);
                        }
                    }
                },

                error: function (data) {
                    layer.msg(data.msg, {icon: 1});
                }

            });


        }, download: function () {   //   下载模板
            var url = baseURL + "sys/jxstudent/downModel?fileName=student.xls";
            window.open(url);//跳转后台的路径
        }
        , deptTree: function () {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    console.log(node);
                    //选择上级部门
                    vm.jxStudent.classId = node[0].deptId;
                    var classId = node[0].deptId;
                    vm.jxStudent.className = vm.parentNames[classId]+"|"+vm.treeMap[classId];
                    var schoolId = vm.getFirstText(vm.parentIds[classId]);
                    vm.jxStudent.schoolId = schoolId;
                    $("#schoolwithclass").val(vm.jxStudent.className);
                    layer.close(index);
                }
            });
        }, getDept: function () {
            //加载部门树
            $.get(baseURL + "sys/dept/select", function (r) {
                console.log(r);
                var first_deptId = r.deptList[0].deptId;   //  第一个id
                ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                var node = ztree.getNodeByParam("deptId", 0);
                node = (node != null ? node : ztree.getNodeByParam("deptId", first_deptId));
                ztree.selectNode(node);
                vm.jxStudent.className = "请选择相应的班级";
                vm.treeData = node;
                vm.getAllParent(vm.treeData);  //  得到所有的父级数据
                console.log(vm.parentNames);
                console.log(vm.parentIds);
                if (vm.jxStudent.classId != undefined) {
                    vm.jxStudent.className = vm.parentNames[vm.jxStudent.classId]+"|"+vm.treeMap[vm.jxStudent.classId];
                }
            })
        }, getAllParent: function (data) {  //  得到所有的父级数据
            vm.treeMap[data.deptId]=data.name;
            debugger;
            if (data.deptId != 0 && data.level == 0) { //  学校
                vm.parentNames[data.deptId] = "";
                vm.parentIds[data.deptId] = 0;
            }
            var ch = data.children;
            if (ch.length > 0) {
                ch.forEach(function (child) {
                    vm.treeMap[child.deptId]=child.name;
                    var pid = data.deptId; //  父级id
                    var pName = data.name; //  父级名称
                    var pPnames = vm.parentNames[pid]; // 父级上一级名称；
                    var pPIds = vm.parentIds[pid];//  父级的上以及id;
                    var dptId = child.deptId;  // 当前id
                    debugger;
                    if (pPnames != undefined) {
                        vm.parentNames[dptId] = pPnames.length > 0 ? pPnames + "|" + data.name : data.name;
                    } else {
                        vm.parentNames[dptId] = data.level > 0 ? data.name : "";
                    }
                    if (pPIds != undefined) {
                        vm.parentIds[dptId] = pPIds + "|" + data.deptId;
                    } else {
                        vm.parentIds[dptId] = data.level > 0 ? data.deptId : "";
                    }
                    if (child.children != undefined) {
                        vm.getAllParent(child);
                    }

                })

            }
        }, getFirstText: function (text) {
            var txts = text.split("|");
            return parseInt(txts[1]);
        }

    }
});